package mi.common.utils;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.persister.entity.AbstractEntityPersister;
/**
 * @ProjectName: [ maven 自动化集成测试系统 ]
 * @Author: [ huanghuanlai ]
 * @CreateTime: [ 2015年5月25日 下午7:15:42 ]
 * @Copy: [ dounine.com ]
 * @Version: [ V1.0 ]
 * @Description: [ hibernate根据类获取表名工具类 ]
 */
public class EntityUtil {
	
	private static Map<String, String> mappings;
	private static Map<String, String> idMappings;
	
	public static void initMappings(SessionFactory sessionFactory) {
	    if (mappings == null) {
	        mappings = new HashMap<String, String>();
	        idMappings = new HashMap<String, String>();
	        SessionFactory factory = sessionFactory;
	        Map<String,ClassMetadata> metaMap = factory.getAllClassMetadata();
	        for (String key : metaMap.keySet()) {
	            AbstractEntityPersister classMetadata = (AbstractEntityPersister) metaMap
	                    .get(key);
	            String tableName = classMetadata.getTableName().toLowerCase();
	            int index = tableName.indexOf(".");
	            if (index >= 0) {
	                tableName = tableName.substring(index + 1);
	            }
	            String className = classMetadata.getEntityMetamodel().getName();
	            String idName = classMetadata.getIdentifierColumnNames()[0];
	            mappings.put(className, tableName);
	            idMappings.put(className, idName);
	        }
	    }
	} 
	
	public static String getIdNameByEntityName(SessionFactory sessionFactory,String entityName) {
	    initMappings(sessionFactory);
	    return idMappings.get(entityName);
	}
	
	public static String getEntityNameByTableName(SessionFactory sessionFactory,String tableName) {
	    initMappings(sessionFactory);
	    return mappings.get(tableName);
	}
}
